package com.spzx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spzx.common.exception.MyException;
import com.spzx.manager.mapper.SysRoleUserMapper;
import com.spzx.manager.mapper.SysUserMapper;
import com.spzx.manager.service.SysUserService;
import com.spzx.model.dto.system.AssginRoleDto;
import com.spzx.model.dto.system.LoginDto;
import com.spzx.model.dto.system.SysUserDto;
import com.spzx.model.entity.system.SysUser;
import com.spzx.model.vo.common.ResultCodeEnum;
import com.spzx.model.vo.system.LoginVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Project: spzx-parent
 * Package: com.spzx.manager.controller.impl
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2023/11/30 20:36
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户登陆
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {

        // 1.校验验证码是否正确
        String captcha = loginDto.getCaptcha();     // 用户输入的验证码
        String codeKey = loginDto.getCodeKey();     // redis中验证码的数据key

/*        // 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        // 判断是否为空，在判断是否不一样
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            throw new MyException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey);*/


        // 2.根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if (sysUser == null) {
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
//            throw new RuntimeException("用户名或者密码错误");
        }

        // 验证登陆密码是否正确
        String inputPassword = loginDto.getPassword();
        // 使用MD5加密
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if (!md5InputPassword.equals(sysUser.getPassword())) {
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
//            throw new RuntimeException("用户名或者密码错误");
        }

        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser), 30, TimeUnit.MINUTES);

        System.out.println("user:login:" + token);

        // 构建响应结果对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        // 返回
        return loginVo;
    }

    /**
     * 获取当前用户信息
     *
     * @param token
     * @return
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    /**
     * 退出登陆
     *
     * @param token
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    /**
     * 用户分页查询接口
     *
     * @param sysUserDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto);
        PageInfo pageInfo = new PageInfo(sysUserList);
        return pageInfo;
    }

    /**
     * 用户添加
     *
     * @param sysUser
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        // 根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.selectByUserName(sysUser.getUserName());
        if (dbSysUser != null) {
            // 判断用户名不重复
            throw new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(1);
        sysUserMapper.saveSysUser(sysUser);
    }

    /**
     * 用户修改
     *
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    /**
     * 用户删除
     *
     * @param userId
     */
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }


    /**
     * 用户分配角色
     *
     * @param assginRoleDto
     */
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {

        // 删除之前的所有的用户所对应的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId -> {
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(), roleId);
        });
    }
}
